import {getSchoolList,addStudent, getMemberList} from '../../../api/member'
import {uploadFile} from '../../../api/upload'
Component({
  data:{
    title:"添加学员",
    sexList:[{
      name:"男",
      value:"0"
    },{
      name:"女",
      value:"1"
    }],
    relationList:[
      {
        name:"父亲",
        value:"0"
      },
      {
        name:"母亲",
        value:"1"
      },
      {
        name:"姥姥",
        value:"2"
      }

    ],
    schoolList:[],
    show:false,
    formData:{
      avatar:"",
      userName:"", 
      nickName:"",
      sex:"",
      familyRel:"",
      idCard:"",
      birthday:"",
      phonenumber:"",
      schoolId:"",  
    },
    SchoolAreaName:"",
    fileList: [],
    // 正则规则
    rule:[
      {
        props:"userName",
        ruleVal:[{
          type:"requierd",
          tooltip:"姓名不能为空",
        }]
      },{
        props:"nickName",
        ruleVal:[{
          type:"requierd",
          tooltip:"昵称不能为空",
        }]
      },{
        props:"sex",
        ruleVal:[{
          type:"requierd",
          tooltip:"请选择性别",
        }]
      },{
        props:"familyRel",
        ruleVal:[{
          type:"requierd",
          tooltip:"请选择关系",
        }]
      },{
        props:"idCard",
        ruleVal:[{
          type:"requierd",
          tooltip:"身份证号不能为空",
        },{
        type:"idCard",
        tooltip:"身份证号格式不正确"
        }
      ]
      },
      {
        props:"birthday",
        ruleVal:[{
          type:"requierd",
          tooltip:"请选择年龄",
        }]
      },
      {
        props:"phonenumber",
        ruleVal:[{
          type:"requierd",
          tooltip:"联系方式不能为空",
        },{
        type:"phone",
        tooltip:"联系方式格式不正确",
        }
      ]
      }
    ]
  },
  methods:{
    onLoad(data:any){
      if(data.childList){
    const res =  JSON.parse(decodeURIComponent(data.childList))
   const formData = this.data.formData as  any
   res.forEach((item:{props:string,value:string}) => {
    formData[item.props] = item.value
   });
   formData.id = Number(data.studentId) 
   const fileList = formData.avatar === "" ? [] : [{
     url:formData.avatar
   }]
    this.setData({
      title:"修改学员信息",
      formData,
      fileList
    })
    
    }
      
      this.getAreaList()
      this.reqSchoolArea()
    },
    showPopup(){
      this.setData({ show: true });
    },
    onClose() {
      this.setData({ show: false });
    },
    // 上传图片
    afterRead(event:any) {
      const { file } = event.detail; // 获取上传的文件对象
      const filePath = file.url; // 获取临时文件路径
      // 调用封装的上传函数
      uploadFile(filePath, 'testUser') // 替换为实际的用户信息
        .then((res) => {
          // 更新图片列表
          this.setData({
            fileList: [{ url: filePath }]
          });
          const {code,data} = JSON.parse( res.data as any)
          if(code === 200){
            wx.showToast({
              title: '上传成功',
              icon: 'success'
            });
            const formData = this.data.formData as any
            formData.avatar = data
            this.setData({
              formData
            })
          }          
        })
        .catch((err) => {
          console.error('上传失败:', err);
          wx.showToast({
            title: '上传失败',
            icon: 'none'
          });
        });
    },
    // 删除头像
    deleteAvatar(){
      const formData = this.data.formData as any
      formData.avatar = ""
      this.setData({
        formData
      })
     this.setData({
      fileList:[]
     })
    },
    // 改变Form表单
    handelChange(e:any){
    const {props,value,id} = e.detail
    let property:any = this.data.formData
    if(["sex","schoolId",'familyRel'].includes(props)){
      property[props] = id
    }else{
      property[props] = value
    }
    this.setData({
      formData:property
    })
    },
    // 提交前校验
    frontCheck(){
      const childComponents = this.selectAllComponents('.form-vant')
      if(childComponents.length > 0){
        const ruleList = this.data.rule as any
        ruleList.forEach((item:any,index:number) => {
          childComponents[index].commonRules(item.props)
        });
       const isPass = childComponents.some((item:any)=>{
        return item.data.isAllPass === false
        })
        return isPass
      }
    },
    
    // 确认提交
    async confirm(){
    //  规则校验
    const isNoPass = this.frontCheck()
    if(isNoPass) return
     const postType = this.data.title === "添加学员" ? true : false;
     const parentId = getApp().getUserInfo().userId
     const postData = this.data.formData as any
     if(postType){
      postData.parentId = parentId
     }
     const {code,data} = await addStudent(postData,postType)
     if(code === 200 && data !== null){
      wx.Utils.toast(`${postType ? '提交':'修改'}成功!`)
     if(postType){
      wx.navigateTo({
        url:`/curriculum_package/pages/studentsDetail/studentsDetail`
      })
     }else{
       wx.navigateBack()
     }

      // 提交成功后获取学员列表存储
      const userId = getApp().getUserInfo().userId
      const {data:memberList} =  await getMemberList({userId:userId})
      getApp().setMemberList(memberList)
     }else{
       wx.Utils.toast("提交失败")
     }
    },
    // 取消提交
    cancel(){
    wx.navigateBack()
    },
        // 获取地区列表
   async getAreaList(){
    const {data:list} =  await getSchoolList()
    const schoolList = list.map((val:{name:string,id:string | number})=>{
      return {
        name:val.name,
        value:val.id.toString()
      }
    })
    const newSchoolList = schoolList.map((val:any)=>{
      return {
        id:val.value,
        name:val.name
      }
    })
    getApp().setSchoolList(newSchoolList)
    this.setData({
      schoolList,
      
    })
  },
  // 查询校区id
  reqSchoolArea(){
   const schoolId = this.data.formData.schoolId
   const schoolList = getApp().getSchoolList()
   const SchoolAreaName = schoolList.filter((val:any)=>{
    return val.id === schoolId
   })[0]?.name || ""
  this.setData({
    SchoolAreaName
  })
  }
  }
})